{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [],
   "source": [
    "'''\n",
    "    function：heap sort \n",
    "    author: fuhongyu\n",
    "    time: 2018-07-28\n",
    "    completion:15 minutes\n",
    "    time complecity:O(n*logn)\n",
    "'''\n",
    "def max_heap(lists, i, size):\n",
    "    lchild = 2*i \n",
    "    rchild = 2*i+1\n",
    "    max = i\n",
    "    if lchild < size and lists[lchild] > lists[max]:\n",
    "        max = lchild\n",
    "    if rchild < size and lists[rchild] > lists[max]:\n",
    "        max = rchild\n",
    "    if max != i:\n",
    "        lists[i] , lists[max] = lists[max], lists[i]\n",
    "        max_heap(lists, max, size)\n",
    "\n",
    "def build_heap( lists):\n",
    "    size = len(lists)\n",
    "    for i in range(0, size//2)[::-1]:\n",
    "        max_heap(lists, i, size)\n",
    "    return lists\n",
    "\n",
    "def heap_sort( lists):\n",
    "    size = len(lists)\n",
    "    lists = build_heap(lists)\n",
    "    print(lists)\n",
    "    for i in range(0, size)[::-1]:\n",
    "        lists[i], lists[0] = lists[0], lists[i]\n",
    "        max_heap(lists, 0 ,i)\n",
    "    print(lists)\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[16, 14, 9, 10, 8, 1, 4, 2, 3, 7]\n",
      "[1, 2, 3, 4, 7, 8, 9, 10, 14, 16]\n"
     ]
    }
   ],
   "source": [
    "lists = [4,1,3,2,16,9,10,14,8,7]\n",
    "heap_sort(lists)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
